package pers.jsan.litheopen.security.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import pers.jsan.litheopen.security.exception.LitheAuthenticationException;
import pers.jsan.litheopen.security.filter.LitheFilterChain;
import pers.jsan.litheopen.security.prover.AuthenticationManager;
import pers.jsan.litheopen.utils.CodeEnum;
import pers.jsan.litheopen.utils.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LitheAccessTokenInterceptor implements HandlerInterceptor {

    private AuthenticationManager authenticationManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        try {
            if(authenticationManager.isClientLoginDisable()) {
                throw new LitheAuthenticationException("用户认证被禁止");
            }
            //授权校验
            LitheFilterChain chain = getAuthenticationManager().getClientFilterChain();
            chain.doFilter(request, response);

        } catch (IOException | ServletException | LitheAuthenticationException | CloneNotSupportedException e) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSONObject.toJSONString(new Result(CodeEnum.AUTHENTICATION_ERROR.get(), null, e.getMessage())));
            return false;
        }
        return true;
    }

    public LitheAccessTokenInterceptor setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        return this;
    }

    public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }
}
